package com.by.controller;

import com.by.common.controller.BaseController;
import com.by.common.entity.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.List;

/*
 * 文件上传
 *
 * */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/v1")
public class UploadController extends BaseController {


    final String DIR = "/attachment";

    /*
     * 单图片上传
     * */
    @ApiOperation("文件上传")
    @ResponseBody
    @PostMapping("/upload/img")
    public ResultBean upload(MultipartFile file, HttpServletRequest request) {
        //非空判断
        if (file.getOriginalFilename() == null) {
            return fail("上传失败");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //生成新的文件名字
        String newFileName = System.currentTimeMillis() + getFileSuffix(fileName);
        //获取服务器的根目录
        String root = request.getServletContext().getRealPath("/");
        File dirFile = new File(root + DIR);
        if (!dirFile.exists()) {
            dirFile.mkdirs();//如果没有该文件就创建文件夹
        }
        //将上传的文件拷贝到指定目录
        try {
            file.transferTo(new File(dirFile, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取保存的文件地址和新文件名
        String path = DIR + "/" + newFileName;
        return success("上传成功", path);
    }


    @ApiOperation("轮播图上传")
    @PostMapping("/upload/carousel")
    public ResultBean uploadCarousel(Object[] arr, HttpServletRequest request) {
        System.out.println(arr);
        return success("1");
    }

    /*
     * 获取文件的后缀
     * */
    String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
